'use strict';

/* Controllers */

var betControllers = angular.module('betControllers', []);

betControllers.controller('plctrl', [
		'$scope',
		'$http',
		'$route',
		'$location',
		function($scope, $http, $route, $location) {
			$http.get('app/soccerfeed/EPL/20').success(function(data) {
				$scope.plmatches = data.matches;
				$scope.plmkeys = Object.keys($scope.plmatches);
			});
			$scope.createEventFromMatch = function(match, mtime) {
				var theoptions = [];
				theoptions[0] = {
					"name" : match.home
				};
				theoptions[1] = {
					"name" : "draw"
				};
				theoptions[2] = {
					"name" : match.away
				};
				var eventToPost = {};
				eventToPost.options = theoptions;
				eventToPost.name = match.home + "-" + match.away;
				//console.log("math is " + match + ", time is " + mtime);
				eventToPost.description = match.home + "-" + match.away + ", "
						+ mtime;
				var millisecs = Date.parse(mtime);
				var thedate = new Date(millisecs);
				var datestr = thedate.getUTCFullYear() + "-"
						+ (thedate.getUTCMonth() + 1) + "-"
						+ thedate.getUTCDate() + "T" + match.status
						+ ":00.000Z";
				eventToPost.category = "SPORT";
				eventToPost.eventtime = datestr;
				eventToPost.betdeadline = datestr;
				postMatchEvent($location, $http, eventToPost, $scope);
			};
		} ]);

betControllers.controller('EventListCtrl', [ '$scope', '$http', '$route',
		'$location', function($scope, $http, $route, $location) {
			$scope.orderProp = 'event.betDeadline';


			checkLoggedOn($scope, $http);
			$scope.eventsWithPot = {};
			// console.log('orderprop is ' + $route.current.orderby);
			$scope.events=[];
			$scope.eventsCounter=0;

			appendToEventList($scope,$http,$scope.eventsCounter,5);


		    $scope.loadMore = function(){
		    	//console.log("loading");
		    	$scope.eventsCounter+=5;
		        appendToEventList($scope,$http,$scope.eventsCounter,5);
		    }

			$scope.searchEvents = function(sq){
			$http.get('app/api/events/search/'+sq).success(function(data) {				
				$scope.events=data;
			});							
			}
		    

			$scope.gotoEvent = function(eventid) {
				$location.path('/events/' + eventid);
			};

			$scope.toggleOrderRecent = function() {
				$scope.orderProp = 'event.betDeadline';
			};

			$scope.toggleOrderPotsize = function() {
				$scope.orderProp = '-event.pot';
			};

		} ]);

betControllers.controller('UserSettingsCtrl', [ '$scope', '$modal', '$http',
		'$route', '$location','$rootScope','$window',
		function($scope, $modal, $http, $route, $location,$rootScope,$window) {
			$scope.orderProp = $route.current.orderby;
			checkLoggedOn($scope, $http);
			$scope.settledbets=[];
			loadMyBets($scope, $http);
			var totaloutstanding=0;
			var trs = $scope.unpaidTransfers;
			for(var i in trs) { totaloutstanding += trs[i].amount; }
			$scope.totaloutstanding=totaloutstanding;	

			$scope.oe=[];
			
			$http.get('app/api/ownevents').success(function(data) {				
				$scope.ownevents = data;
				for(var i=0;i<data.length;i++){
					var anevent = data[i];
					if(anevent.state=='EVENT_DECIDED'){
						$scope.oe.push(anevent);
					}
				}				
			});

			$scope.progressComplete = function() {
				return $scope.settledbets.length>=5;
			};
			
			$scope.gotoEvent = function(eventid) {
				//console.log("clicked");
				$location.path('/events/decide/' + eventid);
			};

			$scope.pay = function() {
				doPayment($http, $scope, $rootScope,$window);
			};

			$scope.setPayPalEmail = function() {
				//console.log("setting ppe ");

				var modalInstance = $modal.open({
					templateUrl : 'ppecontent.html',
					controller : ModalInstanceCtrlsetPPE,
					resolve : {
						sessionplayer : function() {
							return $scope.sessionplayer;
						}
					}
				});
			};

			$scope.$on('UPDATE_SESSION', function() {
				checkLoggedOn($scope, $http);
			});






		} ]);

betControllers.controller('OwnEventsCtrl', [ '$scope', '$http', '$route',
		'$location', function($scope, $http, $route, $location) {
			$scope.orderProp = $route.current.orderby;
			checkLoggedOn($scope, $http);
			$http.get('app/api/ownevents').success(function(data) {
				$scope.ownevents = data;
			});
			$scope.gotoEvent = function(eventid) {
				$location.path('/events/decide/' + eventid);
			};
			$scope.possiblestates = [ {
				"stateq" : "DECIDED",
				"statedesc" : "Event waiting for decision",
				"selected" : "true"
			}, {
				"stateq" : "OPEN",
				"statedesc" : "Open for betting",
				"selected" : "false"
			}, {
				"stateq" : "CLOSED",
				"statedesc" : "Closed for betting",
				"selected" : "false"
			}, {
				"stateq" : "INITIAL",
				"statedesc" : "Initial",
				"selected" : "false"
			}, {
				"stateq" : "SETTLED",
				"statedesc" : "Settled",
				"selected" : "false"
			}, {
				"stateq" : "HISTORIZED",
				"statedesc" : "Archived",
				"selected" : "false"
			} ];
		} ]);

betControllers.controller('MyBetsCtrl', [ '$scope', '$http',
		function($scope, $http) {
			$http.get('app/api/mybets').success(function(data) {
				$scope.mybets = data;
			});
		} ]);



betControllers.controller('ExplainUserStatusCtrl', [ '$scope', '$http',
		function($scope, $http) {
			$scope.isCollapsed = false;
		} ]);

betControllers.controller('scrollCtrl', [ '$scope', '$http',
		function($scope, $http) {
    $scope.items = [];
    $scope.counter = 0;
    $scope.loadMore = function(){
        var i = 1;
        while (i < 50) {
            $scope.items.push(++$scope.counter);
            i++;
        }
    }
    $scope.loadMore();

		} ]);






betControllers.controller('CarouselCtrl', [
		'$scope',
		'$http',
		function($scope, $http) {
			$scope.myInterval = 5000;
			$scope.colors = [ "#fc0003", "#f70008", "#f2000d", "#ed0012",
					"#e80017", "#e3001c", "#de0021", "#d90026", "#d4002b",
					"#cf0030", "#c90036", "#c4003b", "#bf0040", "#ba0045",
					"#b5004a", "#b0004f", "#ab0054", "#a60059", "#a1005e",
					"#9c0063", "#960069", "#91006e", "#8c0073", "#870078",
					"#82007d", "#7d0082", "#780087", "#73008c", "#6e0091",
					"#690096", "#63009c", "#5e00a1", "#5900a6", "#5400ab",
					"#4f00b0", "#4a00b5", "#4500ba", "#4000bf", "#3b00c4",
					"#3600c9", "#3000cf", "#2b00d4", "#2600d9", "#2100de",
					"#1c00e3", "#1700e8", "#1200ed", "#0d00f2", "#0800f7",
					"#0300fc" ];

			$scope.addSlide = function(target, style) {
				var i = target.length;
				target.push({
					label : 'slide #' + (i + 1),
					img : 'http://lorempixel.com/450/300/' + style + '/'
							+ (i % 10),
					color : $scope.colors[(i * 10) % $scope.colors.length],
					odd : (i % 2 === 0)
				});
			};

			$scope.addSlides = function(target, style, qty) {
				for (var i = 0; i < qty; i++) {
					$scope.addSlide(target, style);
				}
			};

			$scope.slides = [];
			$scope.addSlides($scope.slides, 'sports', 50);
		} ]);

betControllers.controller('EventDetailCtrl', [ '$scope', '$routeParams',
		'$http', function($scope, $routeParams, $http) {
			checkLoggedOn($scope, $http);
			loadEventDetails($http, $routeParams, $scope);
			loadBets($http, $routeParams, $scope);
			loadComments($http, $routeParams, $scope);
			$scope.pageTitle = 'Event details';

			$scope.$on('UPDATE_BETS', function() {
				// console.log('received event' + $routeParams.eventId);
				loadBets($http, $routeParams, $scope);
				loadComments($http, $routeParams, $scope);
				loadEventDetails($http, $routeParams, $scope);
				// console.log('done handling event');
			});
		} ]);

betControllers.controller('DecideEventCtrl', [ '$scope', '$routeParams',
		'$http', function($scope, $routeParams, $http) {
			$scope.winnerHasBeenSet = false;
			checkLoggedOn($scope, $http);
			loadEventForDecisionDetails($http, $routeParams, $scope);
			loadBets($http, $routeParams, $scope);
			loadComments($http, $routeParams, $scope);
			$scope.pageTitle = 'Decide event';

		} ]);

betControllers.controller('OptionController', [ '$scope', '$location', '$http',
		'$rootScope', function($scope, $location, $http, $rootScope) {
			$scope.makeBet = function(oid) {
				var data = $scope.bet;
				data.optionid = oid;
				postBet($http, data, $scope, $rootScope);
			};

			$scope.setWinner = function(eid, oid) {
				var data = {};
				data.optionid = oid;
				data.eventid = eid;
				postWinner($location, $http, data, $scope, $rootScope);
			};

		} ]);

betControllers.controller('LikeController', [ '$scope', '$rootScope', '$http',
		function($scope, $rootScope, $http) {
			$scope.likeEvent = function(eid) {
				$http.get('app/api/events/like/' + eid).success(function(data) {
					// console.log('received ' + data);
					$scope.likeResult = data;
					$rootScope.$broadcast('UPDATE_BETS');
				});
			};
		} ]);

betControllers.controller('CommentController', [ '$scope', '$rootScope',
		'$http', function($scope, $rootScope, $http) {
			$scope.commentEvent = function(eid) {
				$http.post('app/api/events/comment', {
					'comment' : this.comment,
					'eventid' : eid
				}).success(function(data) {
					// console.log('received ' + data);
					$scope.commentResult = data;
					$rootScope.$broadcast('UPDATE_BETS');
					$scope.clearcomment();
				});
			};
			var showComments = false;
			$scope.commenton = function() {
				showComments = true;
			};
			$scope.commentoff = function() {
				showComments = false;
			};
			$scope.clearcomment = function() {
				showComments = false;
				$scope.comment = '';
			};
			$scope.showCommentField = function() {
				return showComments;
			};
		} ]);






betControllers.controller('error', [
		'$scope',
		'$http',
		'$routeParams',
		function($scope, $http, $routeParams) {
		 $scope.logonerror=true;
		  $scope.message=$routeParams.message;

		  $scope.closeAlert = function() {
		    $scope.logonerror=false;
		  };	
		} ]);		  



betControllers.controller('SessionController', [
		'$scope',
		'$location',
		'$http',
		'$routeParams',
		function($scope, $location,$http, $routeParams) {
			checkLoggedOn($scope, $http);
			$scope.$on('UPDATE_BETS', function() {
				//console.log('sessioncontroller received event'+ $routeParams.eventId);
				checkLoggedOn($scope, $http);
				// console.log('done handling event');
			});
		$scope.newUser = function(eventid) {
				$location.path('/newuser');
			};
		} ]);

betControllers.controller('newuserCtrl', [
		'$scope',
		'$location',
		'$http',
		'$routeParams',
		function($scope, $location,$http, $routeParams) {
			checkLoggedOn($scope, $http);
			$scope.newuser={};
			$scope.$on('UPDATE_BETS', function() {
				//console.log('sessioncontroller received event'+ $routeParams.eventId);
				checkLoggedOn($scope, $http);
				// console.log('done handling event');
			});
		$scope.ok = function() {
		console.log("ok clcked");

		$http({
			method : 'POST',
			url : 'app/registerNewUser',
			data : JSON.stringify($scope.newuser)
		}).success(function(retd, status, headers, config) {
			// this callback will be called asynchronously
			// when the response is available
			$scope.error_occured = false;
			$scope.retStatus = retd;
			console.log("received" + retd);

			$scope.regok = (retd != null && retd.id != null);
			$scope.error_occured = !$scope.regok;

		}).error(function(data, status, headers, config) {
			// called asynchronously if an error occurs
			// or server returns response with an error status.
			// console.log("received" + data);
			$scope.error_occured = true;
			$scope.retStatus = "Failed registering user: " + headers("errormessage");
		});

	};
			$scope.frontPage = function() {
				$location.path('/');
			};
		} ]);



betControllers.controller('CreateCtrl', [
		'$scope',
		'$location',
		'$http',
		'$routeParams',
		'$rootScope',
		function($scope, $location, $http, $routeParams, $rootScope) {
			$scope.eventToPost = {};
			$scope.categories = [ "POLITICS", "SPORT", "CELEBRITIES",
					"BIG EVENTS", "THIS AND THAT" ];

			$scope.theoptions = [ {
				name : 'Option 1'
			}, {
				name : 'Option 2'
			} ];

			$scope.theinvited = [{email:'emailaddresse'}];

			$scope.deadlinestatus = {
				isBetdeadlineDisabled : false
			};

			$scope.addOption = function() {
				var newItemNo = $scope.theoptions.length + 1;
				$scope.theoptions.push({
					name : 'Option ' + newItemNo
				});
			};

			$scope.removeOption = function() {
				delete $scope.theoptions[$scope.theoptions.length];
				$scope.theoptions.splice($scope.theoptions.length - 1);
			};

			$scope.addInvite = function() {
				var newItemNo = $scope.theinvited.length + 1;
				$scope.theinvited.push({email:'addinvite '+newItemNo});
			};

			$scope.removeInvite = function() {
				delete $scope.theinvited[$scope.theinvited.length];
				$scope.theinvited.splice($scope.theinvited.length - 1);
			};


			$scope.eventToPost.eventtime = new Date();
			$scope.eventToPost.betdeadline = new Date();

			$scope.createEvent = function() {
				$scope.eventToPost.options = $scope.theoptions;
				$scope.eventToPost.invitedList = $scope.theinvited;
				// console.log("theoptions are " + $scope.theoptions[0].name);
				var data = $scope.eventToPost;
				postEvent($location, $http, data, $scope, $rootScope);
			};

		} ]);

betControllers.controller('CollapseCtrl', [ '$scope', function($scope) {
	$scope.isCollapsed = true;
	$scope.toggleCollapse = function() {
		$scope.isCollapsed = !$scope.isCollapsed;
		// console.log('set to ' + $scope.isCollapsed);
		return $scope.isCollapsed;
	};
} ]);




function loadMyBets($scope, $http) {
			$http.get('app/api/mybets').success(function(data) {
				$scope.mybets = data;
				var result = data.filter(function( obj ) {
				  return obj.event.state == 'SETTLED';
				});
				$scope.settledbets = result;
				console.log("setting settled bets to " + result.length);
			});
}

function checkLoggedOn($scope, $http) {
	$http.get('app/api/session/loggedon').success(function(sessionstate) {
		$scope.loggedOn = sessionstate.loggedon;
		$scope.unpaidTransfers=sessionstate.unpaidTransfers;
		if (sessionstate.player != null) {
			$scope.username = sessionstate.player.firstname;
			$scope.sessionplayer = sessionstate.player;
			$scope.ppevar = $scope.sessionplayer.paymentAccount.email;
		}
		if (sessionstate.wallet != null) {
			$scope.credits = sessionstate.wallet.amount;
			// console.log("setting credits to " + $scope.credits);
		}
	});

}

function loadBets($http, $routeParams, $scope) {
	$http.get('app/api/bets/' + $routeParams.eventId).success(
			function(betdata) {
				// console.log('received ' + betdata.length);
				$scope.allbets = betdata;
				var total = 0;
				var lastbets = {};
				for ( var i in betdata) {
					total += betdata[i].amount;
					if (i < 3) {
						lastbets[i] = betdata[i];
					}
				}
				$scope.bets = lastbets;
				$scope.betsTotal = total;
				$scope.betAverage = (total / (betdata.length)).toFixed(2);
				$scope.nOfBets = betdata.length;
			});
}

function loadEventDetails($http, $routeParams, $scope) {
	$http.get('app/api/event/' + $routeParams.eventId).success(function(data) {
		$scope.eventdescriptor = data;
		var numberOfOptions = $scope.eventdescriptor.event.options.length;
		$scope.currentframeheight = 40;
		var myheight = $scope.currentframeheight + ((numberOfOptions - 4) * 5);
		if ($scope.loggedOn) {
			$scope.currentframeheight = '' + myheight + 'em';
		}
		// console.log('currentframeheight is ' + $scope.currentframeheight);
	});
}

function loadEventForDecisionDetails($http, $routeParams, $scope) {
	$http
			.get('app/api/ownevent/' + $routeParams.eventId)
			.success(
					function(data) {
						$scope.eventdescriptor = data;
						var numberOfOptions = $scope.eventdescriptor.event.options.length;
						$scope.currentframeheight = 40;
						var myheight = $scope.currentframeheight
								+ ((numberOfOptions - 4) * 5);
						if ($scope.loggedOn) {
							$scope.currentframeheight = '' + myheight + 'em';
						}
						// console.log('currentframeheight is ' +
						// $scope.currentframeheight);
					});
}

function reverseArr(array) {
	var copy = [].concat(array);
	return copy.reverse();
}

function loadComments($http, $routeParams, $scope) {
	$http.get('app/api/comments/' + $routeParams.eventId).success(
			function(commentsdata) {
				$scope.comments = commentsdata;
				var lastcomments = {};
				for ( var i in commentsdata) {
					if (i < 3) {
						lastcomments[i] = commentsdata[i];
					}
				}
				$scope.comments = lastcomments;
			});
}
function postBet($http, data, $scope, $rootScope) {
	$scope.betfailed = false;
	$scope.betsuccess = false;
	$http({
		method : 'POST',
		url : 'app/addBet',
		data : JSON.stringify(data)
	}).success(function(retd, status, headers, config) {
		// this callback will be called asynchronously
		// when the response is available
		$scope.retStatus = retd;
		// console.log("broadcasting UPDATE_BETS");
		$scope.betsuccess = true;
		$rootScope.$broadcast('UPDATE_BETS');
	}).error(function(data, status, headers, config) {
		// called asynchronously if an error occurs
		// or server returns response with an error status.
		$scope.retStatus = "Failed placing bet: " + headers("errormessage");
		$scope.betfailed = true;
	});
}

function postPPE($http, data, $scope, $rootScope) {
	$scope.ppefailed = false;
	$scope.ppesuccess = false;
	console.log("data is " + JSON.stringify(data));
	$http({
		method : 'POST',
		url : 'app/setppe',
		data : JSON.stringify(data)
	}).success(function(retd, status, headers, config) {
		$scope.retStatus = retd;
		$scope.ppesuccess = true;
		$rootScope.$broadcast('UPDATE_SESSION');
	}).error(
			function(data, status, headers, config) {
				$scope.retStatus = "Failed setting PayPal email: "
						+ headers("errormessage");
				$scope.ppefailed = true;
			});
}

function doPayment($http, $scope, $rootScope, $window) {
	$scope.paymentsuccess = false;
	$scope.paymentfailed = false;	
	$http({
		method : 'POST',
		url : 'app/pay',
		data : JSON.stringify($scope.unpaidTransfers)
	}).success(function(retd, status, headers, config) {
		//console.log("reveived from pay: " + retd);
		$scope.retStatus = retd;
		$scope.paymentsuccess = true;
		$window.location.href='https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-payment&paykey='+retd;
		//$scope.ppwindowurl = $sce.trustAsResourceUrl('https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-payment&paykey='+retd);
		//$scope.showPPWindow=true;
	}).error(
			function(data, status, headers, config) {
				$scope.retStatus = "Failed payment"
						+ headers("errormessage");
				$scope.paymentfailed = true;
			});
}

function postWinner($location, $http, data, $scope, $rootScope) {
	$scope.postWinnerfailed = false;
	$http({
		method : 'POST',
		url : 'app/setWinner',
		data : JSON.stringify(data)
	}).success(function(retd, status, headers, config) {
		// this callback will be called asynchronously
		// when the response is available
		$scope.retStatus = retd;
		// console.log("broadcasting UPDATE_BETS");
		$location.path('/#new');
	}).error(function(data, status, headers, config) {
		// called asynchronously if an error occurs
		// or server returns response with an error status.
		$scope.retStatus = "Failed setting winner: " + headers("errormessage");
		$scope.postWinnerfailed = true;

	});
}





function appendToEventList($scope, $http, from, count) {
			$http.get('app/api/events/'+from+'/'+count).success(function(data) {
				for(var i=0;i<data.length;i++)
				$scope.events.push(data[i]);
			});
}




function postMatchEvent($location, $http, data, $scope) {
	$http({
		method : 'POST',
		url : 'app/postEvent',
		data : JSON.stringify(data)
	}).success(function(retd, status, headers, config) {
		// this callback will be called asynchronously
		// when the response is available
		$scope.retStatus = retd;
		$scope.eventcreatesuccess = true;
		// console.log("event created ok");
		$location.path('/#new');
	}).error(function(data, status, headers, config) {
		// called asynchronously if an error occurs
		// or server returns response with an error status.
		$scope.retStatus = "Failed creating event: " + headers("errormessage");
		$scope.eventcreatefailed = true;

	});
}

function postEvent($location, $http, data, $scope, $rootScope) {
	$scope.eventcreatefailed = false;
	$scope.eventcreatesuccess = false;
	if (!$scope.deadlinestatus.isBetdeadlineDisabled) {
		// console.log("isBetdeadlineDisabled is " +
		// $scope.deadlinestatus.isBetdeadlineDisabled);
		$scope.eventToPost.betdeadline = $scope.eventToPost.eventtime;
	}
	$http({
		method : 'POST',
		url : 'app/postEvent',
		data : JSON.stringify(data)
	}).success(function(retd, status, headers, config) {
		// this callback will be called asynchronously
		// when the response is available
		$scope.retStatus = retd;
		$scope.eventcreatesuccess = true;
		// console.log("event created ok");
		$location.path('/#new');
	}).error(function(data, status, headers, config) {
		// called asynchronously if an error occurs
		// or server returns response with an error status.
		$scope.retStatus = "Failed creating event: " + headers("errormessage");
		$scope.eventcreatefailed = true;

	});
}

betControllers.controller('ModalConfirmBetController', [
		'$rootScope',
		'$scope',
		'$modal',
		'$http',
		function($rootScope, $scope, $modal, $http) {
			$scope.betconfirmed = false;
			$scope.error_occured = false;
			$scope.openBetConfirm = function(evdesc, owo, bet) {
				$scope.owo = owo;
				$scope.evdesc = evdesc;
				$scope.bet = bet;
				bet.optionid = owo.option.id;
				//console.log("sending bet " + JSON.stringify(bet));
				/**
				$http({
					method : 'POST',
					url : 'app/whatif',
					data : JSON.stringify($scope.bet)
				}).success(function(retd, status, headers, config) {
					$scope.whatif = retd;
					$scope.whatiffailed = false;
				}).error(
						function(data, status, headers, config) {
							$scope.retStatus = "Failed whatif: "
									+ headers("errormessage");
							$scope.whatiffailed = true;
						});
**/

				var modalInstance = $modal.open({
					templateUrl : 'confirmBetContent.html',
					controller : ModalInstanceCtrlBet,
					resolve : {
						owo : function() {
							return $scope.owo;
						},
						bet : function() {
							return $scope.bet;
						},
						evdesc : function() {
							return $scope.evdesc;
						},
						whatif : function() {
							return $scope.whatif;
						}
					}
				});
			};

		} ]);

var ModalInstanceCtrlBet = function($rootScope, $scope, $http, $modalInstance,
		owo, bet, evdesc, whatif) {
	$scope.owo = owo;
	$scope.bet = bet;
	$scope.amount = bet.amount;
	$scope.evdesc = evdesc;
	$scope.whatif = whatif;
	//console.log("amount at instance is " + JSON.stringify(owo) + ", amount is "
	//		+ $scope.amount + ", whatif is " + JSON.stringify($scope.whatif));
	$scope.close = function() {
		$modalInstance.close();
	};

	$scope.ok = function() {
		postBet($http, $scope.bet, $scope, $rootScope);
	};
};

var ModalInstanceCtrlsetPPE = function($rootScope, $scope, $http,
		$modalInstance, sessionplayer) {
	$scope.sessionplayer = sessionplayer;
	$scope.ppeval = {};
	$scope.ppeval.p2p=$scope.sessionplayer.p2p;
	$scope.ppeval.email=$scope.sessionplayer.paymentAccount.email;
	$scope.close = function() {
		$modalInstance.close();
	};
	$scope.ok = function(data) {
		postPPE($http, data, $scope, $rootScope);
	};
};
